package logic

import (
	"context"
	"exam/models/cathe"
	"exam/models/mysql"
	"exam/pkg"
	"fmt"

	"exam/examrpc/examrpc"
	"exam/examrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *examrpc.LoginRequest) (*examrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line
	var findUser mysql.User
	mysql.DB.Debug().Where("mobile = ?", in.Mobile).Find(&findUser)
	if findUser.ID == 0 {
		return nil, fmt.Errorf("当前账号未注册，请前去注册")
	}
	if findUser.Password != pkg.Md5(in.Password) {
		return nil, fmt.Errorf("密码错误，请重新输入")
	}
	if in.SmsCode == "" || in.CapCode == "" {
		return nil, fmt.Errorf("短信或图形验证码，不能为空")
	}
	sms := cathe.Rdb.Get(l.ctx, "sendSms"+"login"+in.Mobile)
	if sms.Val() != in.SmsCode {
		return nil, fmt.Errorf("短信验证码输入错误，请重新输入")
	}
	caps := cathe.Rdb.Get(l.ctx, "captcha"+"login"+in.Mobile)
	if caps.Val() != in.CapCode {
		return nil, fmt.Errorf("图形验证码输入错误，请重新输入")
	}
	return &examrpc.LoginResponse{
		Id: int64(findUser.ID),
	}, nil
}
